#coding=utf-8
import logging
from google.appengine.api import mail
from google.appengine.ext import db, webapp
from string import Template

def _render(template, **vars_):
  from string import Template
  return Template(template).substitute(vars_)
  
class Ad(db.Model):
  campaign = db.StringProperty(required=True)
  subject = db.StringProperty(required=True)
  plain_content = db.TextProperty(default='hello')
  html_content = db.TextProperty(required=True)

  flag = db.BooleanProperty(default=False)
  
  created_at = db.DateTimeProperty(auto_now_add=True)
  
  def to_html(self, email):
    return Template(self.html_content).substitute(email=email)

def send_ad(ad, sender, receiver):
  name = receiver.split('@')[0]
  
  subject = _render(ad.subject, name=name)
  body = _render(ad.plain_content, email=receiver)
  html = _render(ad.html_content, email=receiver)
  #logging.info(subject)
  #logging.info(body)
  #logging.info(html)
  mail.send_mail(sender=sender,
    to=receiver,
    subject=subject,
    body=body, 
    html=html)
    
def get_latest_ad():
    return Ad.all().order('-created_at').fetch(1)[0]
    
class AdReceiver(webapp.RequestHandler):
  def post(self):
    a = Ad(campaign = self.request.get('campaign'),
            subject = self.request.get('subject'),
            plain_content = self.request.get('plain'),
            html_content = self.request.get('html'),
            )
    a.put()       
    self.response.out.write(a.to_html('test@gmail.com'))    
